<?php
/**
 *	description:ZMAXWECHAT Sender 帮助类实现文件
 *  author：min.zhang
 *  Email:zhang19min88@163.com
 *	Url:http://www.zmax99.com
 *  copyright:南宁市程序人软件科技有限责任公司保留所有权利
 *  date:2016-05-02
 *  @license GNU General Public License version 3, or later
 */
 
defined('_JEXEC') or die('Restricted access');
jimport("joomla.filesystem.file");

require_once(JPATH_ROOT."/administrator/components/com_zmaxwechat/libs/wechat/token.php");
require_once(JPATH_ROOT."/administrator/components/com_zmaxwechat/libs/wechat/media.php");
require_once(JPATH_ROOT."/administrator/components/com_zmaxwechat/libs/wechat/news.php");
require_once(JPATH_ROOT."/administrator/components/com_zmaxwechat/libs/wechat/material.php");
require_once(JPATH_ROOT."/administrator/components/com_zmaxwechat/libs/db.php");
class zmaxwechatSenderHelper
{
	static public function send()
	{
		//得到队列中所有需要推送的消息
		 $db = JFactory::getDBO();
		 $query = $db->getQuery(true);
		 $query->select("newsqueue_id")->from("#__zmaxwechat_news_map");
		 $db->setQuery($query);
		 $ids = $db->loadcolumn();
		 if(is_array($ids) AND $ids)
		 {
			 $ids = implode(",",$ids);
		 }

		$query = $db->getQuery(true);
		$query->select('n.* ');
		$query->from('#__zmaxwechat_newsqueue AS n');
		if($ids)
		{
			$query->where('n.id NOT IN ('.$ids.')');	
		}
		$db->setQuery($query);
		$items = $db->loadObjectList();
		
		
		$token = new zmaxwechatToken();
		$token = $token->getToken();
		$material = new zmaxwechatMaterial($token->token);		
		$media = new zmaxwechatMedia($token->token);
		
		//将这些信息提交到微信服务器
		//加载Joomla文章的信息
		$article =JTable::getInstance("content");
		$imgPattern ='<img.*?src="(.*?)">';
		$ids = array();
		$news = array();
		
		foreach($items as $item)
		{
			$ids[]=$item->id;
			$article->load($item->article_id);	
			$content = $article->introtext.$article->fulltext;
			preg_match_all($imgPattern,$content,$matches);
			$srcValue = $matches[1];
			
			$newSrc = array();
			foreach($srcValue as $src)
			{
				$newSrc[$src] = $media->uploadImage(JPATH_ROOT.DS.$src);
			}
			
			foreach($newSrc as $old=>$new)
			{
				$content = str_replace($old ,$new,$content);		
			}
			
			//处理引言图片的问题
			
			
			$config = json_decode($item->config);
			
			if($config->thumb_media_id)
			{
				$filePath = $config->thumb_media_id;	
			}else
			{
				$filePath = json_decode($article->images)->image_intro;
			}
			
			
			$introImg = JPath::clean(JPATH_ROOT.DS.$filePath);
			if(!JFile::exists($introImg)) //如果不存在，那么我们需要使用一个默认的图片了
			{
				$defaultIntroImg = "administrator/components/com_zmaxwechat/images/default_intro_img.png";
				$introImg = JPath::clean(JPATH_ROOT.DS.$defaultIntroImg);			
			}
			
		
			$info = $material->getMediaInfo($introImg);
			$new = new stdclass();
			$new->title =   $config->title!=""?$config->title:$article->title;
			$new->thumb_media_id = json_decode($info)->media_id;
			$new->author =  @$config->author!=""?$config->author:"ZMAX微信平台";
			$new->digest =  $config->digest!=""?$config->digest:mb_strimwidth(strip_tags($article->introtext),0,40);
			$new->show_cover_pic=$config->show_cover_pic!=""?$config->show_cover_pic:"1";
			$new->content=$content;
			$new->content_source_url = $config->content_source_url!=""?$config->content_source_url:"http://www.zmax99.com";
			$news[]=$new;							
		}
		
		//得到图文管理对象 添加了一个图文素材了		
		$result = $media->addNews($news);
		
			
		
		if(isset($result->errcode))
		{
			return false;
		}
		
		
		$mediaId = $result->media_id; //该图文消息的mediaID
		
		
		
		
		//更新new map表
		$newsMap = new stdclass();
		$newsMap->media_id = $mediaId;
		$newsMap->date = JDate::getInstance()->toSql();
		$newsMap->count = count($ids);
		$newsMap->newsqueue_id = implode(',',$ids);
		
		$db = JFactory::getDBO();
		$db->insertObject("#__zmaxwechat_news_map" ,$newsMap);
		
		
	
		//更新素材列表
		$item = zmaxwechatDBHelper::checkDuplicate(array("media_id"=>$mediaId),"#__zmaxwechat_news");	
		if($item )
		{
			$item->title = $news[0]->title;
			$item->digest = $news[0]->digest;
			$item->content = json_encode($news);
			$item->update_time = $newsMap->date;
			$item->number = $newsMap->count;
			zmaxwechatDBHelper::updateItem("#__zmaxwechat_news" ,$item ,"id");
		}
		else
		{
			$item = new stdclass();
			$item->media_id= $newsMap->media_id;
			$item->title = $news[0]->title;
			$item->digest = $news[0]->digest;
			$item->content = json_encode($news);
			$item->update_time = $newsMap->date;
			$item->number = $newsMap->count;
			$item->create_time = JDate::getInstance()->toSql();
			zmaxwechatDBHelper::insertItem("#__zmaxwechat_news" ,$item );
		}	
		
		
		//群发出去	
		//检查一下是否该消息已经被提交
		$query = $db->getQuery(true);
		$query->select("date")->from("#__zmaxwechat_sended")->where("media_id='".$mediaId."'");
		$db->setQuery($query);
		$result = $db->loadObject();
		if($result) //如果已经提交了
		{
			//这里需要进一步的处理
			return true;
		}
		
		
		//执行群发功能
		//准备群发过滤器
		$filter = new stdclass();
		$filter->is_to_all=true;
		$filter->tag_id="";
		
		$news = new stdclass();
		$news->media_id = $mediaId;
		
		$result = $media->sendNews($filter ,$news );
		
		if($result->errcode!=0) //发送失败
		{
			return false;
		}
		
		//群发成功，需要将这些内容存储起来
		$sended = new stdclass();
		$sended->submit_state=1;
		$sended->media_id =$mediaId;
		$sended->date = JDate::getInstance()->toSql();
		$sended->result = json_encode($result);
		$sended->msg_id = $result->msg_id;
		$sended->msg_data_id = $result->msg_data_id;
		
		$db->insertObject("#__zmaxwechat_sended" ,$sended);
		return true;
		
	}
}


